//
//  AppOpenAdManager.swift
//  ShouChong
//
//  Created by yw on 2024/9/7.
//

import Foundation
import GoogleMobileAds

class AppOpenAdManager:NSObject {
    var appOpenAd: GADAppOpenAd?
    var isLoadingAd = false
    var isShowingAd = false
    var loadTime: Date?
    let fourHoursInSeconds = TimeInterval(3600 * 4)
    let openADId = "ca-app-pub-9250243293784052/6689027509"
    
    static let shared = AppOpenAdManager()
    
    private func loadAd() async {
        // TODO: Implement loading an ad.
        // Do not load ad if there is an unused ad or one is already loading.
        if isLoadingAd || isAdAvailable() {
            return
        }
        isLoadingAd = true
        
        do {
            appOpenAd = try await GADAppOpenAd.load(
                withAdUnitID: openADId, request: GADRequest())
            loadTime = Date()
        } catch {
            print("App open ad failed to load with error: \(error.localizedDescription)")
        }
        isLoadingAd = false
    }
    
    private func wasLoadTimeLessThanFourHoursAgo() -> Bool {
        guard let loadTime = loadTime else { return false }
        // Check if ad was loaded more than four hours ago.
        return Date().timeIntervalSince(loadTime) < fourHoursInSeconds
    }
    
    
    func showAdIfAvailable() {
        // TODO: Implement showing an ad.
        guard !isShowingAd else { return }
        
        // If the app open ad is not available yet but is supposed to show, load
        // a new ad.
        if !isAdAvailable() {
            Task {
                await loadAd()
            }
            return
        }
        
        if let ad = appOpenAd {
            isShowingAd = true
            ad.present(fromRootViewController: nil)
        }
    }
    
    private func isAdAvailable() -> Bool {
        // Check if ad exists and can be shown.
        return appOpenAd != nil && wasLoadTimeLessThanFourHoursAgo()
    }
}
